package com.graduate.emos.wx.db.dao;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.graduate.emos.wx.db.pojo.MessageEntity;
import com.graduate.emos.wx.db.pojo.MessageRefEntity;
import com.mongodb.client.result.DeleteResult;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Repository
public class MessageDao {
    /*注入MogoTemplate类用来连接MongoDB数据库*/
    @Autowired
    private MongoTemplate mongoTemplate;

    /*插入新数据*/
    public String insert(MessageEntity message) {
        Date sendTime = message.getSendTime();
        /*将北京时间转成格林尼治时间 将北京时间偏移8个小时*/
        sendTime = DateUtil.offset(sendTime, DateField.HOUR, 8);
        message.setSendTime(sendTime);
        /*保存数据到MongoDB*/
        message = mongoTemplate.save(message);
        return message.get_id();
    }

    /*根据分页查询数据*/
    public List<HashMap> searchMessageByPage(int userId, long start, int length) {
        JSONObject json = new JSONObject();
        json.set("$toString", "$_id");
        /*创建用于链接MogoDB集合的对象Aggregation*/
        /*db.message.aggregate([
            {
                $set: {
                    "id": { $toString: "$_id" }
                }
            },
            {
                $lookup:{
                    from:"message_ref",
                    localField:"id",
                    foreignField:"messageId",
                    as:"ref"
                },
            },
            { $match:{"ref.receiverId": 1} },
            { $sort: {sendTime : -1} },
            { $skip: 0 },
            { $limit: 50 }
        ]);*/
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("message_ref", "id", "messageId", "ref"),
                Aggregation.match(Criteria.where("ref.receiverId").is(userId)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC, "sendTime")),
                Aggregation.skip(start),
                Aggregation.limit(length)
        );
        AggregationResults<HashMap> results = mongoTemplate.aggregate(aggregation, "message", HashMap.class);
        List<HashMap> list = results.getMappedResults();

        list.forEach(one -> {
            List<MessageRefEntity> refList = (List<MessageRefEntity>) one.get("ref");
            MessageRefEntity messageRefEntity = refList.get(0);
            Boolean readFlag = messageRefEntity.getReadFlag();
            String refId = messageRefEntity.get_id();
            one.remove("ref");
            one.put("readFlag", readFlag);
            one.put("refId", refId);
            one.remove("_id");
            /*将格林尼治时间转换为北京时间*/
            Date sendTime = (Date) one.get("sendTime");
            sendTime = DateUtil.offset(sendTime, DateField.HOUR, -8);

            /*发送日期显示规则： 如果发送日期是今天 则只显示时间，如果发送时期是今天以前，则发送日期显示为具体日期*/
            String today = DateUtil.today();
            if (today.equals(DateUtil.date(sendTime).toDateStr())) {
                one.put("sendTime", DateUtil.format(sendTime, "HH:mm"));
            } else {
                one.put("sendTime", DateUtil.format(sendTime, "yyyy-MM-dd"));
            }
        });
        return list;
    }

    /*根据id查询消息*/
    public HashMap searchMessageById(String id) {
        HashMap hashMap = mongoTemplate.findById(id, HashMap.class, "message");
        /*将格林尼治时间转换为北京时间*/
        Date sendTime = (Date) hashMap.get("sendTime");
        DateUtil.offset(sendTime, DateField.HOUR, -8);
        hashMap.replace("sendTime", DateUtil.format(sendTime, "yyyy-MM-dd HH:mm"));
        return hashMap;
    }

    public long deleteUserMessage(int receiverId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("receiverId").is(receiverId));
        DeleteResult result = mongoTemplate.remove(query, "message");
        long rows = result.getDeletedCount();
        return rows;
    }

}